/*
 * @Author: Outsider
 * @Date: 2022-05-11 17:08:40
 * @LastEditors: Outsider
 * @LastEditTime: 2022-05-11 22:57:31
 * @Description: In User Settings Edit
 * @FilePath: \Go\wxapp-project\wxapp\code\login\login.go
 */
package login

import (
	"code/token"
	"code/wxappApi"
	"encoding/json"
	"io/ioutil"
	"net/http"
)

type Date struct {
	Code string `json:"code"`
}

type Response struct {
	Code    int64  `json:"code"`
	Message string `json:"message"`
	Type    string `json:"type"`
	Token   string `json:"token"`
}

func Login(w http.ResponseWriter, r *http.Request) {
	// 判断是否为POST请求
	if r.Method != "POST" {
		w.Write([]byte("请使用POST请求！"))
		return
	}

	// 实例化返回结构体
	resp := Response{
		Code:    0,
		Message: "登录成功",
		Type:    "success",
		Token:   "",
	}

	// 获取post过来的数据
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		resp.Code = 400
		resp.Message = err.Error()
		resp.Type = "error"

		// 转换成json格式返回
		result, _ := json.Marshal(resp)
		w.Header().Set("Content-Type", "application/json")
		w.Write(result)
		return
	}
	defer r.Body.Close()

	// 解析post过来的数据成json结构
	var date Date
	json.Unmarshal([]byte(body), &date)

	// 登录
	res := wxappApi.Code2Session(date.Code)
	if res["errcode"] != 0 {
		resp.Code = int64(res["errcode"].(float64))
		resp.Message = res["errmsg"].(string)
		resp.Type = "error"

		// 转换成json格式返回
		result, _ := json.Marshal(resp)
		w.Header().Set("Content-Type", "application/json")
		w.Write(result)
		return
	}

	// 生成token
	user := &token.UserInfo{res["openid"].(string), res["session_key"].(string)}
	t, err := token.GenerateToken(user)
	if err != nil {
		resp.Code = 400
		resp.Message = err.Error()
		resp.Type = "error"

		// 转换成json格式返回
		result, _ := json.Marshal(resp)
		w.Header().Set("Content-Type", "application/json")
		w.Write(result)
		return
	}

	// 转换成json格式返回
	resp.Token = t
	result, _ := json.Marshal(resp)
	w.Header().Set("Content-Type", "application/json")
	w.Write(result)
	return
}
